/*
 * Copyright 2018 Youchaoshi authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common.base.operationHelper;

import android.content.Context;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.io.File;


import common.base.MainApplication;
import common.conf.StaticConf;
import es.dmoral.toasty.Toasty;
import common.base.operationHelper.Interface.OkGoHttpListener;

/**
 * OKGO封装核心方法
 * Created by JustTong on 2018/6/7.
 */
public class OkGoHttp {
    private Context mContext;
    private HttpParams mParams = null;
    private String mUrl;
    private boolean isDebug;

    public OkGoHttp(Context context) {
        this.mContext = context;
        isDebug = StaticConf.IsDebug;
    }

    public OkGoHttp Url(String url) {
        this.mUrl = url;
        return this;
    }

    public OkGoHttp HttpParams(HttpParams params) {
        this.mParams = params;
        return this;
    }

    /**
     * GET请求
     *
     * @param mOkGoHttpListener
     */
    public void Get(final OkGoHttpListener mOkGoHttpListener) {
        OkGo.<String>get(mUrl)
                .tag(mContext)
                .params(mParams)
                .headers("token", MainApplication.UserToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String body = response.body().toString().trim();
                        Logger.e("body:" + body);
                        if (mOkGoHttpListener != null) {
                            try {
                                mOkGoHttpListener.onSuccess(body);
                            } catch (Exception ex) {
                                Logger.e("接口解析或方法异常：1001 Exception>>>" + ex.toString());
//                                Toasty.error(mContext, "异常1001：" + ex.getMessage()).show();
                                Toasty.normal(mContext, "程序开小差！").show();
                            }
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("接口请求异常：1002 onError>>>" + response.body());
//                        Toasty.error(mContext, "异常1002：" + response.body()).show();
                        Toasty.error(mContext, "网络开小差！").show();
                        if (mOkGoHttpListener != null) {
                            mOkGoHttpListener.onError(response.getException().getMessage());

                        }
                    }
                });
    }

    /**
     * 普通的POST请求
     *
     * @param mOkGoHttpListener
     */
    public void Post(final OkGoHttpListener mOkGoHttpListener) {
        OkGo.<String>post(mUrl)
                .tag(mContext)
                .params(mParams)
                .headers("token", MainApplication.UserToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String body = response.body().toString().trim();
//                        PubStatusBean mLoginBean = JsonTool.parseObject(body, PubStatusBean.class);//Gson转Bean
//                        if (mLoginBean.getErrcode() != -100 && mLoginBean.getErrcode() != -101 && mLoginBean.getErrcode() != -102) {
                        if (mOkGoHttpListener != null) {
                            if (isDebug) {
                                mOkGoHttpListener.onSuccess(body);
                            } else {
                                try {
                                    mOkGoHttpListener.onSuccess(body);
                                } catch (Exception ex) {
                                    mOkGoHttpListener.onError(ex.getMessage());
                                    Logger.e("接口解析或方法异常：1001 Exception>>>" + ex.toString());
//                                    Toasty.error(mContext, "接口解析或方法异常：1001 Exception>>>：" + ex.getMessage()).show();
                                    Toasty.normal(mContext, "程序小哥开小差啦！").show();
                                }
                            }
                        }
//                        } else {
//                            //参数备注：-100 登录超时，-101 您的账号已在其它设备登录, -102 登录超时, 1 接口有数据，0 暂无数据
//                            Toasty.error(mContext, mLoginBean.getMessage()).show();
//                            MainActivity.mLoginBean = null;
//                            MainActivity.main.showFragment(0);
//                            PUB.SharedPreferences(mContext, "login_password", "");
//                            mContext.startActivity(new Intent(mContext, LoginActivity.class));
//                            ((Activity) mContext).finish();
//                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Logger.e("接口请求异常：1002 onError>>>" + response.getException().getMessage());
                        Toasty.error(mContext, "接口请求异常：1002 onError>>>：" + response.getException().getMessage()).show();
//                        Toasty.error(mContext, "网络或接口请求异常！").show();
                        if (mOkGoHttpListener != null) {
                            mOkGoHttpListener.onError(response.getException().getMessage());
                        }
                    }
                });

    }

    /**
     * 文件下载
     *
     * @param mOkGoHttpListener 回调
     * @param path              存储路径
     */
    public void GetFile(final OkGoHttpListener mOkGoHttpListener, String path) {
        OkGo.<File>get(mUrl)
                .tag(this)
                .execute(new FileCallback(path) {
                    @Override
                    public void onSuccess(Response<File> response) {
                        Logger.i("getAbsolutePath>>>" + response.body().getAbsolutePath());
                        if (mOkGoHttpListener != null) {
                            mOkGoHttpListener.onSuccess(response.body().getAbsolutePath());
                        }
                    }

                });
    }


}
